/**
 * TraceIdGenerator.java
 * author: yujiakui
 * 2017年12月13日
 * 下午4:13:34
 */
package com.rpay.common.util;

import org.hibernate.id.uuid.CustomVersionOneStrategy;
import org.hibernate.id.uuid.Helper;
import org.hibernate.internal.util.BytesHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

/**
 * Title：   traceId 生成器
 * Description
 *
 * @author fxg06 on 2018/4/18
 * @version 1.0
 */
public class TraceIdGenerator {


    /**
     * hibernate对应的生成id的策略
     */
    private static CustomVersionOneStrategy strategy = new CustomVersionOneStrategy();

    public static String getTraceId() {

        byte[] loBits = new byte[8];

        long sysTime = System.currentTimeMillis();
        short hiTime = (short) (System.currentTimeMillis() >>> 32);
        int loTime = (int) sysTime;
        System.arraycopy(BytesHelper.fromShort(hiTime), 0, loBits, 0, 2);
        System.arraycopy(BytesHelper.fromInt(loTime), 0, loBits, 2, 4);
        System.arraycopy(Helper.getCountBytes(), 0, loBits, 6, 2);

        loBits[0] &= 0x3f;
        loBits[0] |= ((byte) 2 << (byte) 6);

        long leastSignificantBits = BytesHelper.asLong(loBits);

        UUID uuid = new UUID(strategy.getMostSignificantBits(), leastSignificantBits);

        if (uuid.variant() != 2) {
            LoggerUtil.warn("traceId生成有问题：bad variant");
        }
        return uuid.toString();
    }

}
